#!/usr/bin/python
#! encoding:utf8

import zipfile
import tempfile
import re
import os
import shutil
from functools import partial
from sys import version_info
import logging

python_major = tuple(version_info)[0]

def log(message):
    logging.basicConfig(format='%(levelname)s:\t%(message)s', level=logging.DEBUG)
    logging.info(message)

pattern = {
    'Res2App.ear':dict(
        p = 'pf.ws.wsdl.huawei.url.thailand=http://(.*?)/om/omWebService/interfaceService',
        p2 = 'http://(.*?)/',
        target = 'http://{0}/',
        configFile='WEB-INF/classes/Config.properties',),

    'ResFtthApp.war': dict(
        p='pf.ws.wsdl.huawei.url.thailand=http://(.*?)/om/omWebService/interfaceService',
        p2='http://(.*?)/',
        target='http://{0}/',
        configFile='WEB-INF/classes/Config.properties',),

    'ResWebService.war': dict(
        p='\nRES2URL1=t3://(.*?)\n',
        p2='t3://(.*?)\n',
        target='t3://{0}\n',
        configFile='WEB-INF/classes/ejbconfig.properties',),

}

def updateZip(zipname, filename, data):
    # generate a temp file
    tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))
    os.close(tmpfd)

    zin = zipfile.ZipFile(zipname, 'r')
    zout = zipfile.ZipFile(tmpname, 'w')
    zout.comment = zin.comment # preserve the comment
    for item in zin.infolist():
        if item.filename != filename:
            zout.writestr(item, zin.read(item.filename))
    zout.close()
    zin.close()
    # replace with the temp archive
    os.remove(zipname)
    os.rename(tmpname, zipname)

    zf = zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED)
    zf.writestr(filename, data)
    zf.close()
    return zipname


def extract_file_to_temp(zipname, extractname):
    z = zipfile.ZipFile(zipname, 'r')
    tfname = z.extract(extractname, tempfile.gettempdir())
    return tfname



def replace_host(src, host, pattern_key):
    p = pattern.get(pattern_key).get('p')
    p2 = pattern.get(pattern_key).get('p2')
    target = pattern.get(pattern_key).get('target')

    target_url = re.sub(p2, target.format(host), p)
    src_url = re.search(p,src)
    result = re.sub(p, target_url, src)
    if src_url is not None:
        log('replace {0}  to  {1} \n'.format(src_url.group().strip(), target_url.strip()))
    else:
        log('replace fail! pattern {0} can not match in {1} \n'.format(p, src))
    return result

def get_src_configuration_data(zipFileName, configFile_path, encode='utf-8'):
    zf = zipfile.ZipFile(zipFileName, 'r')
    config_file_str = zf.read(configFile_path).decode(encode)
    zf.close()
    return config_file_str

def get_modified_configuration_data(zipFileName, configFile_path, host, pattern_key, encode='utf-8'):
    config_file_str = get_src_configuration_data(zipFileName, configFile_path, encode=encode)
    replaced_config_str = replace_host(config_file_str, host, pattern_key)
    return replaced_config_str.encode(encode)


def modify_configfile_in_zip(zipFileName, configFile_path, host, pattern_key, encode='utf-8'):
    log('start modify {0} !'.format(zipFileName))
    data = get_modified_configuration_data(zipFileName, configFile_path, host, pattern_key, encode=encode)
    updateZip(zipFileName,configFile_path, data)
    log('modify {0} over !'.format(zipFileName))
    return


def modify_ftthApp(filename, host, encode='gbk'):
    pattern_key = 'ResFtthApp.war'

    configFile = pattern.get(pattern_key).get('configFile')
    modify_configfile_in_zip(filename,configFile,host,pattern_key,encode)


def modify_ResWebService(filename, host, encode='gbk'):
    pattern_key = 'ResWebService.war'
    configFile = pattern.get(pattern_key).get('configFile')
    modify_configfile_in_zip(filename,configFile,host,pattern_key,encode)


def modify_res2app(filename, host, encode='gbk'):
    #zpfile = os.path.split(filename)[-1]
    pattern_key = 'Res2App.ear'

    log('start modify {0} !'.format(filename))
    r2w_arcname = 'Res2Web.war'
    r2wtempname = extract_file_to_temp(filename, r2w_arcname)

    configFile = pattern.get(pattern_key).get('configFile')
    modify_configfile_in_zip(r2wtempname, configFile, host, pattern_key, encode)

    with open(r2wtempname,'rb') as data:
        updateZip(filename, r2w_arcname, data.read())
    log('modify {0} over !'.format(filename))

def clear():
    try:
        shutil.rmtree(Res2App)
        shutil.rmtree(ResFtthApp)
        shutil.rmtree(ResWebService)
    except:
        pass

    shutil.copyfile('Res2App - 副本.ear', Res2App)
    shutil.copyfile('ResFtthApp - 副本.war', ResFtthApp)
    shutil.copyfile('ResWebService - 副本.war', ResWebService)



def check_src_and_target_url(src, host, pattern_key, filename):
    p = pattern.get(pattern_key).get('p')
    p2 = pattern.get(pattern_key).get('p2')
    target = pattern.get(pattern_key).get('target')

    target_url = re.sub(p2, target.format(host), p)
    src_url = re.search(p,src)
    log('check: {0} \n'.format(filename))
    if src_url is not None:
        log('we will replace [{0}]  to  [{1}] \n'.format(src_url.group().strip(), target_url.strip()))
    else:
        log('pattern [{0}] can not match ,please check the configuration file is curret !\n'.format(p))
    return src_url  , target_url


def check():
    pattern_key = 'ResWebService.war'
    filename = ResWebService
    host = IM_dev_host
    configFile = pattern.get(pattern_key).get('configFile')
    data = get_src_configuration_data(filename, configFile,   encode='gbk')
    check_src_and_target_url(data, host, pattern_key, filename)

    pattern_key = 'ResFtthApp.war'
    filename = ResFtthApp
    host = OM_host
    configFile = pattern.get(pattern_key).get('configFile')
    data = get_src_configuration_data(filename, configFile,   encode='gbk')
    check_src_and_target_url(data, host, pattern_key, filename)

    pattern_key = 'Res2App.ear'
    filename = Res2App
    host = OM_host
    configFile = pattern.get(pattern_key).get('configFile')
    r2w_arcname = 'Res2Web.war'
    r2wtempname = extract_file_to_temp(filename, r2w_arcname)
    data = get_src_configuration_data(r2wtempname, configFile, encode='gbk')
    check_src_and_target_url(data, host, pattern_key, filename)

    if python_major < 3 :
        confirm = raw_input('continue ? (y/n)')
    else:
        confirm = input('continue ? (y/n)')
    if confirm == 'n':
        exit()



if __name__ == '__main__':
    Res2App = '/root/Oracle/Middleware/user_projects/app/Res2App.ear'
    ResFtthApp = '/root/Oracle/Middleware/user_projects/domains/rescfg_domain/servers/AdminServer/upload/ResFtthApp.war'
    ResWebService = '/root/Oracle/Middleware/user_projects/app/ResWebService.war'
    IM_dev_host = '192.168.240.13' + ':6666'
    OM_host = '192.168.240.15' + ':8012'

    # clear()
    check()
    modify_res2app(Res2App, OM_host)
    modify_ftthApp(ResFtthApp, OM_host)
    modify_ResWebService(ResWebService, IM_dev_host )
